package com.guoj.rabbitmq.service.impl;

import com.alibaba.fastjson.JSON;
import com.guoj.rabbitmq.entity.BrokerMessageLog;
import com.guoj.rabbitmq.entity.TOrder;
import com.guoj.rabbitmq.mapper.TOrderMapper;
import com.guoj.rabbitmq.sender.RabbitOrderSender;
import com.guoj.rabbitmq.service.IBrokerMessageLogService;
import com.guoj.rabbitmq.service.ITOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guoj.rabbitmq.utils.Constant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guoj
 * @since 2019-05-31
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {
	@Resource
	private ITOrderService orderService;
	@Resource
	private IBrokerMessageLogService brokerMessageLogService;
	@Resource
	private RabbitOrderSender orderSender;

	@Override
	public void createOrder(TOrder order) {

		LocalDateTime now = LocalDateTime.now();

		// 业务数据入库
		orderService.save(order);

		// 构建消息日志记录对象
		BrokerMessageLog messageLog = new BrokerMessageLog();
		messageLog.setMessageId(order.getMessageId());
		messageLog.setMessage(JSON.toJSONString(order));
		messageLog.setStatus(Constant.ORDER_SENDING);
		messageLog.setNextRetry(now.plusMinutes(Constant.ORDER_TIMEOUT_MINUTES));
		messageLog.setCreateTime(now);
		messageLog.setUpdateTime(now);
		// 消息日志对象入库
		brokerMessageLogService.save(messageLog);

		// rabbitmq 发送消息
		orderSender.sendOrder(order);
	}
}
